<template>
  <div class="page-container">
     <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>自动化营销</el-breadcrumb-item>
        <el-breadcrumb-item>用户旅程</el-breadcrumb-item>
        <el-breadcrumb-item>用户旅程列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar" >
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <!-- <el-row class="times mr30"> --><el-form-item  style="margin-bottom:0 !important">
            <el-form-item prop="startTime" label="旅程时间：" style="margin-right:0 !important">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="开始时间"
                class="input_postion"
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
             <span class="line">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="结束时间"
                class="input_postion"
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item></el-form-item>
          <!-- </el-row> -->
          <!-- <el-form-item prop="selectName" label="所属组织："  v-show=" deptType == 0 || deptType == 1">
            <treeselect style="width: 178px" :normalizer="normalizer" :options="options" v-model="selectName" noChildrenText="" clearValueText="" placeholder="请选择" noResultsText="暂无数据"
              :clearable="false" :deselect="deselect()" :default-expand-level="3" :searchable="true" @select="selectDept"/>
          </el-form-item> -->
          <el-form-item prop="tripName" label="旅程名称：" >
            <el-input clearable v-model="filters.tripName" placeholder="旅程名称" maxlength="80"></el-input>
          </el-form-item>
        </el-row>
        <!--操作按钮-->
        <el-row class="search-button">
          <el-form-item>
            <kt-button :label="$t('action.reset')" class="resetButton" @click="resetForm('filters')" icon="el-icon-refresh"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="el-icon-search" label="搜索" class="searchButton" @click="findPage" />
          </el-form-item>
          <el-form-item>
            <kt-button label="创建用户旅程" @click="createPage()" perms="crm:trip:add" class="searchButton" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <div class="tab-container">
      <!-- tbs标签 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane v-for="item in tabMapOptions" :key="item.key" :label="item.label" :name="item.key">
        </el-tab-pane>
      </el-tabs>
      <!-- jic table表格-->
      <div class="toolbar" >
        <!--表格显示列界面-->
        <table-column-filter-dialog
          ref="tableColumnFilterDialog"
          :columns="columns"
          @handleFilterColumns="handleFilterColumns"
        ></table-column-filter-dialog>
      </div>
      <!--表格内容栏-->
      <jic-table
        ref="JicTable"
        :data="pageResult"
        :operationWidth="380"
        :totalSize="totalSize"
        :columns="filterColumns"
        :showCopyDataOperation="false"
        :showCopyLinkOperation="false"
        :showDetailOperation="true"
        :showBatchDelete="false"
        :loading="loading"
        :btnList="btnList"
        @findPage="findPage"
        @handleDetail="handleDetail"
        @colseTrip="colseTrip"
        @deleteTrip="deleteTrip"
        @updateTrip="updateTrip"
        ></jic-table>
    </div>

  </div>
</template>

<script>
import KtButton from "@/views/Core/KtButton";
import JicTable from "./AutoMarketTable";
import { format } from "@/utils/datetime";
import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
import { darkmagenta } from "color-name";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Tab",
  components: {
    KtButton,
    JicTable,
    Treeselect,
    TableColumnFilterDialog,
  },
  data() {
    return {
      deptType: localStorage.getItem('deptType'),
      // 用户旅程结束时间校验
      timeCheck: {
        disabledDate: time => {
          if (this.filters.startTime!=null && this.filters.startTime!='' && this.filters.startTime!= undefined) {
            return time.getTime() < new Date(this.filters.startTime) - 8.64e7
          }
        }
      },
      tabMapOptions: [
        { label: "全部", key: '0' },
        { label: "待开始", key: '1' },
        { label: "进行中", key: '2' },
        { label: "已结束", key: '3' },
        { label: "已关闭", key: '4' },
        { label: "草稿", key: '5' }
      ],
      columns:[
        { prop: "tripCode", label: "ID", minWidth: 290 },
        { prop: "tripName", label: "旅程名称", minWidth: 200 },
        { prop: "deptName", label: "所属组织", minWidth: 100},
        { prop: "status", label: "状态", minWidth: 100 ,formatter:function(row, column, cellValue, index){
          //状态 1 待提交 2 待审核 3 审核不通过 4 进行中 5 已过期 6 已关闭 7 未开始 8 已结束 9 用户旅程草稿
          if (row.status == "1") {
              return "待开始";
          } else if (row.status == "2") {
            return "进行中";
          } else if (row.status == "3") {
            return "已结束";
          } else if (row.status == "4") {
            return "已关闭";
          } else if (row.status == "5") {
            return "草稿";
          }
        }},
        { prop: "startTime", label: "旅程时间", minWidth: 350 ,formatter:function(row, column, cellValue, index){
          //用户旅程开始结束时间拼接
          if(row.timeType == 1 ){
            return row.startTime + " - " + row.endTime;
          }else{
            return " - ";
          }
        }},
        { prop: "createTime", label: "创建时间", minWidth: 290 }
      ],
      //列表按钮
      btnList:[{
          "customLabel":"编辑",
          "isShowMethod":"1,5",
          "method":"updateTrip",
          "perms":"crm:trip:edit"
        },{
          "customLabel":"关闭",
          "isShowMethod":"1,2,5",
          "method":"colseTrip",
          "perms":"crm:trip:close"
        },{
          "customLabel":"删除",
          "isShowMethod":"1,5",
          "method":"deleteTrip",
          "perms":"crm:trip:delete"
        }],
      pageResult: {},
      filterColumns: [],
      totalSize:0,
      pageRequest:{},
      loading:true,
      activeName: "0",
      size: "small",
      filters: {
        startTime:'',
        endTime:'',
        tripName:'',
      },
      selectName: null,
      selectDepart: {},
      clearOnSelect: true,
      options: [],
      startDateDisabled: {},//开始时间限制
      endDateDisabled: {},//结束时间限制
    };
  },
  methods: {

    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },

    // 获取当前选中部门的名称
    selectDept(val) {
      this.selectDepart = val;
      this.selectName = val.id;
    },
    //查询条件渲染
    findDeptTree(){
      let that = this;
      this.utils.request.getAuthorDeptTree({}, res => {
        if (res.code == "0000" && res.data) {
          that.options = res.data;
          that.selectName = localStorage.getItem('deptId');
        }
      });
    },
    //格式化组织初查询条件
    normalizer(node) {
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      }
    },
    //所属组织 清楚选择后
    deselect(){
      if(this.selectName == undefined || this.selectName == null){
        this.selectName = null;
        this.findDeptTree();
      }
    },
    // 获取分页数据
    findPage: function(data) {
      //子组件传过来的分页参数 data.start 当前页 data.limit 当前页总条数
      this.loading = true;
      if(data != null && data.start != null){
        if(data.start != null){
          this.pageRequest.pageNum = data.start;
        }
        if(data.limit != null){
          this.pageRequest.pageSize = data.limit;
        }
      }
      let this_ = this;
      if (this_.filters == undefined || this_.filters == null) {
        this_.filters = {};
      }
      this_.filters.start = this.pageRequest.pageNum;
      this_.filters.limit = this.pageRequest.pageSize;
      this_.filters.deptId = this.selectName==null? localStorage.getItem('deptId') : this.selectName;
      this.utils.request.queryTripList(this_.filters, function (res) {
      this_.loading = false;
        if (res.data.rows.length < 1) {
          res.data.rows = [];
          res.data.total = 0;
        }
        this_.$refs.JicTable.findPage({content:res.data.rows,total:res.data.total});
      });
    },
    createPage() {
      this.$router.push({path:"/pages/AutoMarket/UserJourneyManagement/SetRule"});
    },
    //查看
    handleDetail: function(data) {
      this.$router.push({path: `/pages/AutoMarket/UserJourneyManagement/checkJourney?id=${data.row.id}`});
    },
    updateTrip: function(data) {
      if(data.row.status == 5 ){
        this.$router.push({path: `/pages/AutoMarket/UserJourneyManagement/SetRule?id=${data.row.id}&isdraft=1`})
      }else{
        this.$router.push({path: `/pages/AutoMarket/UserJourneyManagement/SetRule?id=${data.row.id}&isdraft=0`})
      }
      
    },
    // 删除用户旅程
    deleteTrip: function(data) {
      this.$confirm('<p>您确定要删除该用户旅程？</p><p style="color:red">删除后不可恢复</p>', "提示", {
        type: "warning",
        dangerouslyUseHTMLString: true,
        closeOnClickModal: false,
      }).then(() => {
        if (data != null && data.row != null) {
          var params = {};
          params.id = data.row.id;
          var this_ = this;
          this.utils.request.deleteTripInfo(params, function(res) {
            if (res.code == "0000") {
              this_.$message({ message: "删除成功！", type: "success" });
              this_.findPage(null);
            } else {
              this_.$message({ message: "操作失败, " + res.msg, type: "error" });
            }
          });
        }
      }).catch(() => {
      });
    },
    //关闭用户旅程
    colseTrip: function(data) {
      let params = {};
      params.id = data.row.id;
      params.status = 6;//关闭状态为0
      var this_ = this;
      this.$confirm('<p>您确定要关闭该用户旅程？</p><p style="color:red">关闭后将结束本次用户旅程</p>', "提示", {
        type: "warning",
        dangerouslyUseHTMLString: true,
        closeOnClickModal: false,
      }).then(() => {
        this.utils.request.closeTripInfo(params, function(res) {
          if (res.code == "0000") {
            this_.$message({message: "关闭成功！ ", type: "success"});
            this_.findPage(null);
          } else {
            this_.$message({ message: "操作失败, " + res.msg, type: "error" });
          }
        });
      }).catch(() => {
      });
    },
    // 时间格式化
    dateFormat: function(row, column, cellValue, index) {
      return format(row[column.property]);
    },
    //重置
    resetForm(formName) {

      //需要校验的keys
			let keys = ["startTime","endTime","tripName"]
      //调用校验
      let dataForm = this.filters;
			let booFlag = true;
      if(dataForm == null || keys == null){
          return true;
      }else{
          booFlag = true;
          for (const key in dataForm) {
              if (dataForm.hasOwnProperty(key) && keys.indexOf(key) != -1) {
                  const value = dataForm[key];
                  if(value != null &&  value != ''){
                      //证明有值
                      booFlag = false;
                      break;
                  }
              }
          }
      }
      if(booFlag && this.selectName == localStorage.getItem('deptId')){
          this.$message({message: "请输入查询条件", type: "warning" });
          return false;
      }
      this.selectName = localStorage.getItem('deptId');
      this.filters.deptId = localStorage.getItem('deptId');
      if (this.$refs[formName] != undefined) {
        this.$refs[formName].resetFields();
        this.findPage();
      }
    },

    // 处理表格列过滤显示
    displayFilterColumnsDialog: function() {
      this.$refs.tableColumnFilterDialog.setDialogVisible(true);
    },
    // 处理表格列过滤显示
    handleFilterColumns: function(data) {
      this.filterColumns = data.filterColumns;
      this.$refs.tableColumnFilterDialog.setDialogVisible(false);
    },
    // 处理表格列过滤显示
    initColumns: function() {
      var temp = [];
      $.each(this.columns, function(key, val) {
        temp.push(val);
      });
      this.filterColumns = temp;
    },
  },
  watch: {
    activeName(val) {
      if(val != '0'){
        this.filters.status = val;
      }else{
        this.filters.status = null;
      }
      this.findPage();
    },

  },
  created() {
    // init the default selected tab
    const tab = this.$route.query.tab
    if (tab) {
      this.activeName = tab
    }
  },
  mounted() {
    this.initColumns();
    this.findDeptTree();
  }
};
</script>

<style scoped lang="scss">
  .reset {
    background-color: #fff;
    color: #409eff;
  }
 
</style>
